/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Card;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;
import model.VehicleCategory;

/**
 *
 * @author Aggelos
 */
public class ListProgramForm extends javax.swing.JFrame
{

    EntityManager em;
    JFrame thisFrame;
    Program program;
    int s;

    /**
     * Creates new form ListProgramForm
     */
    public ListProgramForm()
    {
        em = DBManager.em;
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
          }
        initComponents();
        setLocationRelativeTo(null);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        programsQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select p from Program p");
        programsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(programsQuery.getResultList());
        stationsQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(stationsQuery.getResultList());
        vehicleCategoryQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select vc from VehicleCategory vc");
        vehicleCategoryList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(vehicleCategoryQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        programsTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        newButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programsList, programsTable, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(programsTable);
        programsTable.getColumnModel().getColumn(0).setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
        jLabel1.setText("Πίνακας Προγραμμάτων");

        newButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newButton.setText("Νέος");
        newButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                newButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteButton.setText("Διαγραφή");
        deleteButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                deleteButtonActionPerformed(evt);
            }
        });

        editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editButton.setText("Επεξεργασία");
        editButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                editButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jSeparator1))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deleteButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(editButton))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 41, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addComponent(saveButton)
                .addGap(18, 18, 18)
                .addComponent(cancelButton)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSeparator2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newButton)
                    .addComponent(deleteButton)
                    .addComponent(editButton))
                .addGap(18, 18, 18)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        // TODO add your handling code here:
        program = new Program();
        em.persist(program);


        List<ProgramRate> prList = program.getProgramRateList();

        if (prList == null)
          {
            prList = new ArrayList<ProgramRate>();
            program.setProgramRateList(prList);
          }

        for (Station s : stationList)
          {
            for (VehicleCategory vc : vehicleCategoryList)
              {
                ProgramRate pr = new ProgramRate();

                pr.setCategoryId(vc);
                pr.setStationId(s);
                pr.setProgramId(program);
                em.persist(pr);

                program.getProgramRateList().add(pr);
              }
          }
        // em.getTransaction().commit();

        EditProgramForm epf = new EditProgramForm(program, false);

        epf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //************
        epf.addWindowListener(new WindowListener()
        {
            public void windowClosed(WindowEvent arg0)
            {
                System.out.println("Window close event occur");
                if (((MyWindowEvent) arg0).exitAndSave)
                  {


                    programsList.add(program);
                    int row = programsList.size() - 1;

                    programsTable.setRowSelectionInterval(row, row);
                    programsTable.scrollRectToVisible(programsTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                  }
                else
                  {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = programsQuery.getResultList();
                    for (Object entity : data)
                      {
                        em.refresh(entity);
                      }
                    programsList.clear();
                    programsList.addAll(data);
                  }
            }

            public void windowActivated(WindowEvent arg0)
            {
                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0)
            {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0)
            {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0)
            {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0)
            {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0)
            {
                System.out.println("Window Opened");
            }
        });


    }//GEN-LAST:event_newButtonActionPerformed

    public List<Card> retrieveCardByProgram(Program p2)
    {

        String strSQL = "select j from Card j where j.programId=:programId";
        Query cardQuery = em.createQuery(strSQL)
                .setParameter("programId", p2);

        List<Card> cL = cardQuery.getResultList();

        return cL;
    }


    public void deleteProgrameRateByProgram(Program pp)
    {
        String strSQL = "delete  from ProgramRate j where j.programId=:programId";
        Query delQuery = em.createQuery(strSQL)
                .setParameter("programId", pp);
        delQuery.executeUpdate();
    }

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int s = programsTable.getSelectedRow();
        if (s >= 0)
          {
            Program p = programsList.get(programsTable.convertRowIndexToModel(s));
            // programsList.remove(p);
            // em.remove(p);


            List<Card> cardL = new ArrayList<Card>();

            cardL = retrieveCardByProgram(p);

            if (!cardL.isEmpty())
              {
                JOptionPane.showMessageDialog(this, "Δεν μπορει να διαγραφει το προγραμμα. \n "
                        + "Υπάρχουν οχήματα που το χρησιμοποιούν",
                        "Διαγραφή", JOptionPane.ERROR_MESSAGE);

              }
            else if (cardL.isEmpty())
              {
                System.out.println("μπορεις να διαγράψεις");

                deleteProgrameRateByProgram(p);
                programsList.remove(p);
                em.remove(p);
              }


          }

    }//GEN-LAST:event_deleteButtonActionPerformed

    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed

        s = programsTable.getSelectedRow();
        if (s >= 0)
          {
            program = programsList.get(s);
            EditProgramForm ecf = new EditProgramForm(program, true);

            ecf.setVisible(true);
            thisFrame = this;
            thisFrame.setEnabled(false);
            //************
            ecf.addWindowListener(new WindowListener()
            {
                public void windowClosed(WindowEvent arg0)
                {
                    System.out.println("Window close event occur");
                    if (((MyWindowEvent) arg0).exitAndSave)
                      {

                        //    em.merge(program);
                        programsList.set(s, program);
                        programsTable.setRowSelectionInterval(s, s);
                        programsTable.scrollRectToVisible(programsTable.getCellRect(s, 0, true));
                        thisFrame.setEnabled(true);
                      }
                    else
                      {
                        thisFrame.setEnabled(true);
                        em.getTransaction().rollback();
                        em.getTransaction().begin();
                        java.util.Collection data = programsQuery.getResultList();
                        for (Object entity : data)
                          {
                            em.refresh(entity);
                          }
                        programsList.clear();
                        programsList.addAll(data);
                      }
                }

                public void windowActivated(WindowEvent arg0)
                {
                    System.out.println("Window Activated");
                }

                public void windowClosing(WindowEvent arg0)
                {
                    System.out.println("Window Closing");
                }

                public void windowDeactivated(WindowEvent arg0)
                {
                    System.out.println("Window Deactivated");
                }

                public void windowDeiconified(WindowEvent arg0)
                {
                    System.out.println("Window Deiconified");
                }

                public void windowIconified(WindowEvent arg0)
                {
                    System.out.println("Window Iconified");
                }

                public void windowOpened(WindowEvent arg0)
                {
                    System.out.println("Window Opened");
                }
            });
          }
    }//GEN-LAST:event_editButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
//        em.getTransaction().rollback();
//        em.getTransaction().begin();
//        dispose();
        if (em.getTransaction().isActive())
          {
            em.getTransaction().rollback();
          }
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
            em.getTransaction().rollback();
          }

        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, false);
        for (WindowListener l : this.getWindowListeners())
          {
            l.windowClosed(we);
          }
        this.setVisible(false);

    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
       
        em.getTransaction().commit();
     em.getTransaction().begin();
     dispose();



    }//GEN-LAST:event_saveButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
          {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
              {
                if ("Nimbus".equals(info.getName()))
                  {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                  }
              }
          }
        catch (ClassNotFoundException ex)
          {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (InstantiationException ex)
          {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (IllegalAccessException ex)
          {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
          {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new ListProgramForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JButton newButton;
    private java.util.List<Program> programsList;
    private javax.persistence.Query programsQuery;
    private javax.swing.JTable programsTable;
    private javax.swing.JButton saveButton;
    private java.util.List<Station> stationList;
    private javax.persistence.Query stationsQuery;
    private java.util.List<VehicleCategory> vehicleCategoryList;
    private javax.persistence.Query vehicleCategoryQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
